package com.htandroid.htandroid.aty;

import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.ab.soap.AbSoapListener;
import com.ab.soap.AbSoapParams;
import com.ab.soap.AbSoapUtil;
import com.ab.task.AbTask;
import com.ab.task.AbTaskItem;
import com.ab.task.AbTaskObjectListener;
import com.ab.util.AbDialogUtil;
import com.ab.util.AbToastUtil;
import com.ab.view.ioc.AbIocView;
import com.htandroid.htandroid.R;
import com.htandroid.htandroid.global.MyApplication;
import com.htandroid.reconstitute.base.ConstanceHeTai;
import com.htandroid.reconstitute.base.ConstanceHttp;
import com.htandroid.reconstitute.utils.SpUtil;
import com.htandroid.reconstitute.utils.ToastUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.LinkedHashMap;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import okhttp3.Call;

import static com.htandroid.htandroid.constance.ConstanceServer.BaseUrl_New;

/**
 * Created by lkp on 2015/11/29.
 * 服务器设置页面
 */
public class ServerSettings extends MyBaseActivity {
    private MyApplication application;
    private String url = null;
    private String code = null;
    private String registrationId = null;
    private AbSoapUtil mAbSoapUtil = null;

    @AbIocView(id = R.id.settings_btn_ok, click = "btnClick")
    TextView btnOk;
    @AbIocView(id = R.id.settings_url)
    EditText seturl;
    @AbIocView(id = R.id.settings_code)
    EditText setcode;
    @AbIocView(id = R.id.registrationId)
    TextView tv_registrationId;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setAbContentView(R.layout.layout_serversettings);
        application = (MyApplication) abApplication;
        titleBar.setBackgroundColor(Color.parseColor("#f1f1f1"));
        titleBar.setLogo(R.mipmap.back_2);
        tv_registrationId.setTextIsSelectable(true);



//        seturl.setText(application.mSharedPreferences.getString("server_url", "120.27.154.113:8080"));
//        setcode.setText(application.mSharedPreferences.getString("server_code", "123456"));

        String address = SpUtil.getString(ServerSettings.this, ConstanceHeTai.login_server_address);
        String code = SpUtil.getString(ServerSettings.this, ConstanceHeTai.login_server_code);


        seturl.setText(address);
        setcode.setText(code);

        initId();
        mAbSoapUtil = AbSoapUtil.getInstance(this);
        mAbSoapUtil.setTimeout(10000);
    }

    public void btnClick(View v) {
        url = seturl.getText().toString();
        code = setcode.getText().toString();
        if (url.isEmpty()) {
            AbToastUtil.showToast(ServerSettings.this, R.string.toast_ss_urlrequired);
            return;
        }
        if (code.isEmpty()) {
            AbToastUtil.showToast(ServerSettings.this, R.string.toast_ss_coderequired);
            return;
        }

        Map<String,String> map=new LinkedHashMap<>();
        map.put("psw", code);

        checkServer(map, ConstanceHttp.base_url+url+ConstanceHttp.sysabout_address_check,url);//检查服务器配置
//        abCheck();
    }

    private void checkServer(final Map<String,String> mParams, String mUrl, String server) {
        OkHttpUtils.post().url(mUrl).params(mParams).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                String message = e.getMessage();
                ToastUtil.showToast("服务异常-"+message);

            }

            @Override
            public void onResponse(String response, int id) {
                String string = response.toString();
                if (response!=null&&!response.isEmpty()&&response.contains("true")){
                    ToastUtil.showToast("验证通过");
                    SpUtil.putString(ServerSettings.this, ConstanceHeTai.login_server_address, url);
                    SpUtil.putString(ServerSettings.this,ConstanceHeTai.login_server_code , mParams.get("psw"));
                    finish();
                }else {
                    ToastUtil.showToast("验证失败");
                }

            }
        });

    }

    public void initId() {
        if (application.getRegistrationId() == null || application.getRegistrationId() == "" ||
                "null".equalsIgnoreCase(application.getRegistrationId())) {
            JPushInterface.setDebugMode(true);
            JPushInterface.init(getApplicationContext());
            if (JPushInterface.isPushStopped(getApplicationContext())) {
                JPushInterface.resumePush(getApplicationContext());//恢复极光推送
            }
            registrationId = JPushInterface.getRegistrationID(this);
            tv_registrationId.setText(registrationId);
            application.setRegistrationId(registrationId);
        } else {
            tv_registrationId.setText(application.getRegistrationId());
        }
    }

    private void abCheck() {
        AbTask task = new AbTask();
        final AbTaskItem item = new AbTaskItem();
        item.setListener(new AbTaskObjectListener() {

            @Override
            public <T> void update(T entity) {
                AbDialogUtil.removeDialog(ServerSettings.this);
                String nameSpace = "http://service.test.com";
                String methodName = "addresscheck";
                String urlString = "http://" + url + BaseUrl_New;//旧版webservice地址
                AbSoapParams params = new AbSoapParams();
                params.put("arg0", code);
                mAbSoapUtil.call(urlString, nameSpace, methodName, params, new AbSoapListener() {
                    //获取数据成功会调用这里
                    @Override
                    public void onSuccess(int statusCode, String content) {
                        if (content != null) {
                            if (content != null) {
                                if (content.contains("false")) {
                                    AbToastUtil.showToast(ServerSettings.this, R.string.errorcode);
                                    return;
                                }
                                SharedPreferences.Editor pEdit = application.mSharedPreferences.edit();
                                pEdit.putString("server_url", url);
                                pEdit.putString("server_code", code);
                                pEdit.commit();
                                AbToastUtil.showToast(ServerSettings.this, R.string.savesuceed);
                                finish();
                            } else {
                                AbToastUtil.showToast(ServerSettings.this, R.string.sqlerrormsg);
                            }
                        }
                    }

                    // 失败，调用
                    @Override
                    public void onFailure(int statusCode, String content,
                                          Throwable error) {
                        AbDialogUtil.removeDialog(ServerSettings.this);
                        AbToastUtil.showToast(ServerSettings.this, R.string.toast_server_error);
                    }

                    // 开始执行前
                    @Override
                    public void onStart() {
                        //显示进度框
                        AbDialogUtil.showProgressDialog(ServerSettings.this, 0, "正在加载...");
                    }

                    // 完成后调用，失败，成功
                    @Override
                    public void onFinish() {
                        //移除进度框
                        AbDialogUtil.removeDialog(ServerSettings.this);
                    }
                });
            }

            @SuppressWarnings("unchecked")
            @Override
            public Integer getObject() {
                return -1;
            }
        });
        task.execute(item);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            this.finish();
        }
        return false;
    }
}
